import { defineStore } from 'pinia';
import { docsApi } from '@/services/api';
import { useConfigStore } from './config';

export const useDocsStore = defineStore('docs', {
  state: () => ({
    items: [],
    searchResults: [],
    total: 0,
    loading: false,
    lastQuery: '',
    tags: [],
    error: null
  }),
  actions: {
    async fetchDocs(opts = {}) {
      this.loading = true;
      this.error = null;
      try {
        const config = useConfigStore();
        config.loadFromStorage();
        const response = await docsApi.list({ headers: config.authHeaders, params: opts });
        this.items = response.docs;
        this.total = response.count;
      } catch (error) {
        this.error = error;
        console.error('Failed to fetch docs', error);
      } finally {
        this.loading = false;
      }
    },
    async createDoc(payload) {
      const config = useConfigStore();
      config.loadFromStorage();
      const response = await docsApi.create({ headers: config.authHeaders, data: payload });
      await this.fetchDocs();
      return response.doc;
    },
    async updateDoc(id, payload) {
      const config = useConfigStore();
      config.loadFromStorage();
      const response = await docsApi.update(id, { headers: config.authHeaders, data: payload });
      await this.fetchDocs();
      return response.doc;
    },
    async deleteDoc(id) {
      const config = useConfigStore();
      config.loadFromStorage();
      await docsApi.remove(id, { headers: config.authHeaders });
      await this.fetchDocs();
    },
    async searchByText(query, tags = []) {
      this.loading = true;
      this.error = null;
      try {
        const config = useConfigStore();
        config.loadFromStorage();
        this.lastQuery = query;
        this.tags = tags;
        const response = await docsApi.search({
          headers: config.authHeaders,
          params: { q: query, tags: tags.join(',') }
        });
        this.searchResults = response.results;
        return response.results;
      } catch (error) {
        this.error = error;
        console.error('Search failed', error);
        throw error;
      } finally {
        this.loading = false;
      }
    },
    async searchByVector(vector, limit = 5) {
      const config = useConfigStore();
      config.loadFromStorage();
      const response = await docsApi.searchByVector({
        headers: config.authHeaders,
        data: { vector, limit }
      });
      this.searchResults = response.results;
      return response.results;
    }
  }
});
